<?php
declare(strict_types=1);

namespace app\common\business;

use think\Exception;
use think\facade\Log;

class BusiBase
{
    public $model = null;

    /**
     * 返回分页空数据数组
     *
     * @param int $number
     * @return array
     */
    public function returnNullDataArray(int $number = 10)
    {
        return [
            'total' => 0,
            'per_page' => $number,
            'current_page' => 1,
            'data' => []
        ];
    }

    /**
     * 商品列表页返回空数据数组
     *
     * @param int $number
     * @return array
     */
    public function returnNullListGoodsArray(int $number = 10)
    {
        return [
            'total_page_num' => 0,
            'count'          => 0,
            'page'           => 0,
            'page_size'      => $number,
            'list'           => []
        ];
    }

    /**
     * 根据 ID 获取当前模型数据
     *
     * @param int $id
     * @return array
     */
    public function getById(int $id, $field = true)
    {
        if (!$id) return [];
        try {
            $result = $this->model->field($field)->find($id);
        } catch (\Exception $e) {
            $this->errorLog("find data by id $id error: ".$e->getMessage());
            return [];
        }
        return $result->toArray();
    }

    /**
     * 数据新增部分
     *
     * @param array $data
     * @return mixed
     * @throws Exception
     */
    public function insert(array $data, string $operate_user = null)
    {
        $data['status'] = config('status.mysql.table_normal');
        $data['operate_user'] = $operate_user ?? session(config('admin.session_admin'))['username'];
        try{
            $this->model->save($data);
        } catch (\Exception $e) {
            $this->errorLog("insert data false, data:". json_encode($data)."; error: ".$e->getMessage());
            throw new Exception('服务器内部异常'.$e->getMessage());
        }
        return $this->model->id;
    }

    /**
     * 根据 ID 修改数据
     *
     * @param int $id
     * @param array $data
     * @return mixed
     * @throws Exception
     */
    public function edit(int $id, array $data)
    {
        // 判断 id 是否为空，待修改数据是否为空、数组
        if (empty($id) || empty($data) || !is_array($data)) throw new Exception('待修改数据错误');

        $data['update_time'] = time();
        try{
            $res = $this->model->where('id', $id)->save($data);
        } catch (\Exception $e) {
            $this->errorLog("update data $id to ".json_encode($data));
            $this->errorLog("update data $id error: ".$e->getMessage());
            $this->errorLog('');
            throw new Exception('服务器内部错误');
        }
        return $res;
    }

    /**
     * 批量修改数据
     *
     * @param array $condition
     * @param array $data
     * @return mixed
     * @throws Exception
     */
    public function editAll(array $condition, array $data)
    {
        // 判断条件和待修改数据是否为空
        if (!$condition || !$data || !is_array($condition) || !is_array($data)) throw new Exception('待修改数据错误');

        $data['update_time'] = time();
        try {
            $res = $this->model->where($condition)->save($data);
        } catch (\Exception $e) {
            $this->errorLog('editAll '.json_encode($condition)." to ".json_encode($data)." error: ".$e->getMessage());
            throw new Exception('服务器内部错误');
        }
        return $res;
    }

    /**
     * 检查当前数据是否存在
     *
     * @param int $id
     * @return array
     * @throws Exception
     */
    public function checkDataById(int $id)
    {
        // 获取当前数据
        $data = $this->getById($id);
        // 判断当前数据是否为空
        if (!$data) throw new Exception('该数据不存在');
        return $data;
    }

    /**
     * 根据分类 ID 修改分类状态
     *
     * @param int $id
     * @param int $status
     * @return bool
     * @throws Exception
     */
    public function updateStatusById(int $id, int $status)
    {
        // 检查当前数据是否存在
        $data = $this->checkDataById($id);

        // 判断数据状态是否需要修改
        if ($data['status'] == $status) throw new Exception('当前状态无需修改');

        $res = $this->edit($id, ['status' => $status]);
        return $res;
    }

    /**
     * 根据 Id 修改分类数据排序
     *
     * @param int $id
     * @param int $listorder
     * @return bool
     * @throws \think\Exception
     */
    public function updateListorderById(int $id, int $listorder)
    {
        // 检查当前数据是否存在
        $data = $this->checkDataById($id);

        $update = $this->edit($id, ['listorder' => $listorder]);
        return $update;
    }

    /**
     * 通过 ID 数组获取对应数据信息
     *
     * @param array $idArr
     * @param bool $field
     * @return array
     */
    public function getNormalByIdArr(array $idArr = [], $field = true)
    {
        if (!$idArr) return [];
        try {
            $res = $this->model->getNormalByIdArr($idArr, $field);
        } catch (\Exception $e) {
            $this->errorLog('find normal data by '.json_encode($idArr)." error: ".$e->getMessage());
            return [];
        }
        $result = $res->toArray();
        if (!$result) return [];
        return $result;
    }

    /**
     * 根据数据 ID 删除数据
     *
     * @param int $id
     * @return false
     */
    public function deleteDataById(int $id)
    {
        try {
            $delete = $this->model->destroy($id);
        } catch (\Exception $e) {
            $this->errorLog("delete by $id error: ".$e->getMessage());
            return false;
        }
        return $delete;
    }

    /**
     * 记录当前模型错误日志
     *
     * @param string $error
     */
    public function errorLog(string $error)
    {
        Log::error(get_class($this)." $error");
    }

}